import React, { Component } from "react";
//import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import themeUtil from "@tools/theme";
import verCode from "@component/verCode/index";
import BankItem from "./bankItem.js";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList,
	checkUserBankInfo,
	checkBonus
} from "@redux/Action/bank/bank";
import { InterfaceG } from "@config/Config";
//import BackModal from "@component/backModal/index";
import Notice from "@component/notice/notice";
import yhTools from "@tools/yh";
import iconXj from "@images/icon-xj1.png";
import { getAppPlatformsDatas } from "@redux/Action/nativeDatas/nativeDatas";
const BankIcon = require("@images/icon/helpTip1.png");

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);
const checkIdCard = value => /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
const phoneSeparated = value => {
	let tel = "";
	if (value) {
		tel =
			value.substring(0, 3) +
			" " +
			value.substring(3, 7) +
			" " +
			value.substring(7, 11);
	}
	return tel;
};
const agreementPageMap = {
	1: "/personalInformationLicense",
	2: "/personalCreditAuthorization"
};
const alert = Modal.alert;

@verCode()
@connect(
	state => ({
		bonusStr: state.bankReducer.bonusStr,
		supportedBankList: state.bankReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer,
		longitude: state.getAppPlatformsDatas.longitude,
		latitude: state.getAppPlatformsDatas.latitude,
		mobile: state.getAppPlatformsDatas.mobile
	}),
	dispatch => ({
		checkBonus: (val1, val2) => dispatch(checkBonus(val1, val2)),
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun)),
		checkUserBankInfo: (value, fun) => dispatch(checkUserBankInfo(value, fun)),
		_getAppPlatformsDatas: value => dispatch(getAppPlatformsDatas(value))
	})
)
class xhfAddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			idCard: "",
			isVisible: false,
			accountNo: "",
			verifyCode: "",
			channelCode: "YHB",
			userBankPhone: props.mobile ? phoneSeparated(props.mobile) : "",
			messageSerialNumber: "",
			verifier: "",
			from: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			spaceID: "",
			inputDisabled: false
		};
	}
	componentWillReceiveProps = nextProps => {
		//props 更新
		const {
			userBankPhone,
			accountNo,
			idCard,
			userName,
			inputDisabled
		} = nextProps.pageParams;
		if (nextProps.pageParams.inputDisabled) {
			this.setState({
				userBankPhone,
				accountNo,
				idCard,
				userName,
				inputDisabled
			});
		}
	};
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	keyboardEvent = obj => {
		const id = document.activeElement.getAttribute("id");
		if (id !== "fix-cursor") {
			let winHeight = document.documentElement.clientHeight;
			if (document.getElementById(`keybordb_${this.state.spaceID}`)) {
				document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
					(winHeight * obj.heightper) / 2 + 74 + "px";
			}
		}
		if (id === "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};
	componentDidMount = () => {
		// 宝付贷版本用的是YHB 换卡是ll连连, 连连是120s倒计时，华通是60s
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	};
	isHasLocation() {
		const _this = this;
		let longitude = this.props.longitude || "";
		let latitude = this.props.latitude || "";
		if (!longitude || !latitude) {
			//获取经纬度
			window.YHAuthorize.callHandler("Privacy_Loaction", "", res => {
				// if (res.status == "1000") {
				const { data = {} } = res;
				longitude = data.longitude || "";
				latitude = data.latitude || "";
				_this.props._getAppPlatformsDatas({ longitude, latitude });
				// } else if (res.status == "3001") {
				// 	alert("地理位置授权", "允许永辉金融钱包访问您当前的地理位置信息？", [
				// 		{ text: "取消", onPress: () => {} },
				// 		{ text: "设置", onPress: () => this.openLoction() }
				// 	]);
				// } else {
				// 	Toast.info(res.message, 2);
				// }
			});
		}
	}

	//去设置允许打开地理位置
	openLoction() {
		yhTools.settingPrivacy();
	}
	//选择图片
	chooseImage() {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName: this.props.mobile + "_card_" + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				this.getOcrBank(resp.data.path);
			},
			() => {}
		);
	}

	//获取ocr银行卡
	getOcrBank(path) {
		const imageData = {
			name: "bankImg.jpeg",
			path: path,
			params: {}
		};
		const objs = {
			url: InterfaceG.orcBank,
			imageArray: [imageData]
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					bankInfo: res.data,
					accountNo: res.data.cardNumber
						.replace(/\s/g, "")
						.replace(/(\w{4})(?=\w)/g, "$1 ")
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}

	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	getMsgCode = () => {
		this.sendMsgCode();
	};
	sendMsgCode = () => {
		const { lnid } = this.props;
		const { accountNo, userBankPhone, idCard, userName } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!accountNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(accountNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!idCard) {
			Toast.info("请输入身份证", 2);
			return false;
		}
		if (!checkIdCard(submitCardRegexp(idCard))) {
			Toast.info("身份证格式不正确", 2);
			return false;
		}
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(120); //连连验证码时间
		let objs = {
			url: InterfaceG.xhfGetVerifyCode,
			params: {
				mobilePhone: submitCardRegexp(userBankPhone),
				accountName: submitCardRegexp(userName),
				accountNo: submitCardRegexp(accountNo),
				idCard: submitCardRegexp(idCard),
				lnid
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { orderNo, status } = res.data;
				this.setState({
					orderNo,
					status,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	xhfAddBank = () => {
		const { lnid, applyNo, orderNo } = this.props;
		const {
			accountNo,
			verifyCode,
			userBankPhone,
			idCard,
			userName
		} = this.state;
		if (
			this.checkCanSubmit(
				accountNo,
				userBankPhone,
				verifyCode,
				idCard,
				userName
			)
		) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.xhfbindCard,
				params: {
					accountName: submitCardRegexp(userName),
					idCard: submitCardRegexp(idCard),
					lnid,
					accountNo: submitCardRegexp(accountNo),
					verifyCode: submitCardRegexp(verifyCode),
					userBankPhone: submitCardRegexp(userBankPhone),
					applyNo,
					orderNo
				},
				_alertShow: false
			};
			this.props.Submit(objs);
			this.setState({
				canSubmit: true
			});
		}
	};
	InputOnChange = (key, value) => {
		console.log(key, value);
		this.setState({
			[key]: value
		});
	};
	checkCanSubmit = (cardNo, phoneNum, verifyCode, idCard, userName) => {
		if (this.state.inputDisabled) {
			return true;
		} else {
			if (!userName) {
				Toast.info("请输入姓名", 2);
				return false;
			}
			if (!cardNo) {
				Toast.info("请输入银行卡号", 2);
				return false;
			}
			if (!checkBankReg(submitCardRegexp(cardNo))) {
				Toast.info("请输入正确的银行卡号", 2);
				return false;
			}
			if (!idCard) {
				Toast.info("请输入身份证", 2);
				return false;
			}
			if (!checkIdCard(submitCardRegexp(idCard))) {
				Toast.info("身份证格式不正确", 2);
				return false;
			}
			if (!phoneNum) {
				Toast.info("请填写手机号", 2);
				return false;
			}
			if (!checkPhoneReg(submitCardRegexp(phoneNum))) {
				Toast.info("手机号格式不正确", 2);
				return false;
			}
			if (!this.state.hasSendCode) {
				Toast.info("请获取验证码", 2);
				return false;
			}
			if (!verifyCode.length) {
				Toast.info("请输入验证码");
				return false;
			}
			if (verifyCode.length !== 6) {
				Toast.info("验证码输入错误");
				return false;
			}
			return true;
		}
	};
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.checkSetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return true;
		} else if (res.code === "70010") {
			return false;
		} else {
			Toast.info(res.message, 2);
			return null;
		}
	}
	addNewBankFn = async () => {
		// 防止重复提交，待优化
		const {
			channelCode,
			accountNo,
			userBankPhone,
			verifyCode,
			messageSerialNumber,
			verifier,
			idCard,
			userName
		} = this.state;
		if (
			this.checkCanSubmit(
				accountNo,
				userBankPhone,
				verifyCode,
				idCard,
				userName
			)
		) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.addNewCard,
				params: {
					channelCode,
					accountNo,
					userBankPhone,
					verifyCode,
					messageSerialNumber,
					verifier
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(res => {
				this.setState({ canSubmit: true });
				Toast.hide();
				if (res.code === "0") {
					this.props.getSelectedBankList({ channelCode });
					setTimeout(() => {
						this.props.history.goBack();
					}, 0);
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	saveBank = () => {
		this.xhfAddBank();
	};

	//查看协议
	openContract = type => {
		const { userName, idNo } = this.props.ocrInfo;
		const year = new Date().getFullYear();
		const month = new Date().getMonth() + 1;
		const day = new Date().getDate();
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		this.props.pageParams.history.push({
			pathname: agreementPageMap[type],
			params: type === "huaTongAccount" ? paramsHuaTong : commonParams
		});
	};
	updateBank = () => {
		if (!this.state.inputDisabled) {
			this.chooseImage();
		}
	};
	render() {
		const {
			isVisible,
			userBankPhone,
			accountNo,
			hasSendCode,
			idCard,
			userName,
			inputDisabled
		} = this.state;
		const { supportedBankList, bonusStr } = this.props;
		const { countDown, isClick } = this.props.verCode;
		return (
			<div className="add-bank-containers-warpper">
				<div className="add-bank-containers">
					{/* 如果派券活动奖励为空字符串则不显示，默认空字符串 */}
					{bonusStr && <Notice noticeContent={bonusStr} />}
					{themeUtil.getTheme() == "yhLife" && (
						<img
							className="header-img"
							src={
								this.props.pageParams ? this.props.pageParams.headerBanner : ""
							}
						/>
					)}
					{themeUtil.getTheme() == "yhLife" && (
						<div className="progress-container">
							<p className="progress-title">
								已填写 <em>80%</em> 最高5万元信用额度
							</p>
							<div className="progress-bg">
								<span className="progress-line"></span>
							</div>
						</div>
					)}
					<InputItem
						className="my-input"
						value={userName}
						disabled={inputDisabled}
						placeholder="请输入姓名"
						maxLength={10}
						id="js-fix-bug"
						onChange={this.InputOnChange.bind(this, "userName")}
					>
						姓名
					</InputItem>
					{/* 23包括空格 */}
					<InputItem
						maxLength="23"
						className="my-input my-clear1"
						placeholder="请输入银行卡号"
						type="bankCard"
						id="js-fix-bug"
						disabled={inputDisabled}
						clear
						value={accountNo}
						onChange={this.InputOnChange.bind(this, "accountNo")}
					>
						银行卡号
						{!inputDisabled ? (
							<img
								src={iconXj}
								className="icon-xj"
								onClick={() => this.updateBank()}
							/>
						) : null}
						<img
							alt="guide"
							className="icon-help"
							src={BankIcon}
							onClick={() => this.toggleVisible(true)}
						/>
					</InputItem>
					<InputItem
						clear
						maxLength={18}
						type="text"
						id="js-fix-bug"
						placeholder="请输入身份证号码"
						value={idCard}
						disabled={inputDisabled}
						className="my-input"
						onChange={this.InputOnChange.bind(this, "idCard")}
					>
						身份证号码
					</InputItem>
					<InputItem
						clear
						type="phone"
						id="js-fix-bug"
						placeholder="请填写预留手机号"
						disabled={inputDisabled}
						value={userBankPhone || this.props.pageParams.userBankPhone}
						className="my-input"
						onChange={this.InputOnChange.bind(this, "userBankPhone")}
					>
						预留手机号
					</InputItem>
					{!inputDisabled ? (
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							id="js-fix-bug"
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-clear2"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.getMsgCode}>
								{/* {isClick ? "获取验证码" : countDown} */}

								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
					) : null}
					<Modal
						visible={isVisible}
						transparent
						maskClosable={true}
						title="银行卡支持列表"
						closable={true}
						onClose={() => this.toggleVisible(false)}
						className="bank-list-modal"
					>
						<div style={{ height: 300, overflow: "scroll" }}>
							{supportedBankList.map(item => (
								<BankItem item={item} key={Math.random()} />
							))}
						</div>
					</Modal>
				</div>
				<div className="button-wrapper">
					<div className="agree-wrapper">
						<span className="multi-line">
							<p className="huise">点击按钮，表示您已阅读并同意</p>
							<p className="xieyi-p">
								<a className="xieyi" onClick={() => this.openContract("1")}>
									《个人信息授权书》
								</a>
								<a className="xieyi" onClick={() => this.openContract("2")}>
									《个人征信授权书》
								</a>
							</p>
						</span>
					</div>
					<Button style={{ marginTop: "0.2rem" }} onClick={this.saveBank}>
						{!inputDisabled ? "确认绑定" : "下一步"}
					</Button>
					<div id={"keybordb_" + this.state.spaceID}></div>
				</div>
			</div>
		);
	}
}
export default xhfAddBank;
